<template>
  <div :style="{ height: tableHeight + 'px', background: '#ffffff' }">
    <ContentWrap>
      <div class="btnWrap routeHeader">
        <div>
          <el-button
          v-hasPermi="['produce:production-prepare:save']"
            v-if="
              route.query.type == 'update' ||
              route.query.type == 'createShipmentOrder' ||
              route.query.type == 'create'
            "
            @click="saveData"
            type="primary"
            >保存</el-button
          >
          <el-button
          v-hasPermi="['produce:production-prepare:submit']"
            v-if="
              route.query.type == 'update' ||
              route.query.type == 'createShipmentOrder' ||
              route.query.type == 'create'
            "
            @click="submitData"
            type="primary"
            >提交</el-button
          >
          <el-button
          v-hasPermi="['produce:production-prepare:cancle']"
            v-if="route.query.type == 'update' || route.query.type == 'createShipmentOrder'"
            @click="cancelData"
            style="color:red"
            >作废</el-button
          >
          <el-button v-hasPermi="['produce:production-prepare:withdraw']" v-if="route.query.type == 'proofread'" @click="withdraw" style="color:red"
            >撤回</el-button
          >
          <el-button @click="close">关闭</el-button>
        </div>
      </div>
    </ContentWrap>

    <ContentWrap>
      <div>基本信息</div>
      <el-form class="-mb-5px" :model="queryParam" :inline="true" label-width="110px">
        <el-form-item label="订单号" prop="orderNumber">
          <div class="select-wrapper">
            <el-input v-model="queryParam.orderNumber" disabled class="!w-220px" />
            <span
              class="search-icon"
              v-if="
                route.query.type != 'createShipmentOrder' &&
                route.query.type != 'proofread' &&
                route.query.type != 'detail'
              "
              @click="handQueryOrder()"
            >
              <Icon icon="ep:search" />
            </span>
          </div>
        </el-form-item>
        <el-form-item label="订单类型" prop="dictOrderType">
          <el-select
            v-model="queryParam.dictOrderType"
            placeholder="请选择订单类型"
            clearable
            class="!w-220px"
            disabled
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.MARKET_ORDER_TYPE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="queryParam.customerCode" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParam.customerName" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="产品编码" prop="productNumber">
          <el-input v-model="queryParam.productNumber" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParam.productName" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input v-model="queryParam.productStandard" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="清单编号" prop="prepareNumber">
          <el-input v-model="queryParam.prepareNumber" class="!w-220px" disabled />
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div class="btnWrap">
        <div>清单明细</div>
        <div>
          <el-button type="primary" @click="chooseComponent()" v-if="route.query.type == 'create'||route.query.type == 'update'||route.query.type == 'createShipmentOrder'">选择部件</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="list" border>
        <el-table-column type="index" width="55" label="序号" align="center" fixed="left"/>
        <!-- 列定义 -->
        <el-table-column align="left" width="180">
          <template #header>
            <span>部件编码</span>
          </template>
          <template #default="scope"> {{ scope.row.partNumber }} </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span>部件名称</span>
          </template>
          <template #default="scope"> {{ scope.row.partName }} </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span>图纸图号</span>
          </template>
          <template #default="scope"> {{ scope.row.partDrawingNumber }} </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span>部件规格</span>
          </template>
          <template #default="scope"> {{ scope.row.partSpecification }} </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span>生产数量</span>
          </template>
          <template #default="scope">
            <span>{{ scope.row.incomingRemaQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>备货数量</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'prepareQuantityView'"
              name="prepareQuantityView"
              v-model="scope.row.prepareQuantity"
              placeholder="请输入备货数量"
              type="number"
              :min="0"
              :max="100"
              class="!w-140px"
              :disabled="route.query.type == 'proofread' || route.query.type == 'detail'"
            />
          </template>
        </el-table-column>
        <el-table-column align="left" width="180">
          <template #header>
            <span>单位</span>
          </template>
          <template #default="scope"> {{ scope.row.partUnit }} </template>
        </el-table-column>
        <el-table-column label="备注" align="left" width="180">
          <template #default="scope">
            <el-input
              v-nextInput="'remarkView'"
              name="remarkView"
              v-model="scope.row.remark"
              placeholder="请输入备注"
              class="!w-140px"
              :disabled="route.query.type == 'proofread' || route.query.type == 'detail'"
            />
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" align="left" width="180">
          <template #default="scope"> {{ scope.row.warehouseName }} </template>
        </el-table-column>
        <el-table-column label="操作" align="left" min-width="110" fixed="right">
          <template #default="scope">
            <!-- 删除按钮 -->
            <el-button
              v-if="route.query.type === 'create'||route.query.type === 'createShipmentOrder' || ['20','10'].includes(route.query.dictPrepareStatus) "
              link
              type="danger"
              @click="deleteRow(scope.$index)"
              >删除行</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <ContentWrap  v-if="route.query.dictPrepareStatus ==40 || route.query.dictPrepareStatus ==50 || route.query.dictPrepareStatus ==10">
      <div v-if="route.query.dictPrepareStatus ==40 || route.query.dictPrepareStatus ==50 || route.query.dictPrepareStatus ==10">
        <div>校对意见</div>
        <el-form class="-mb-5px" :model="proofread" :inline="true" label-width="110px">
          <div>
            <el-form-item label="校对人" prop="proofreaderName">
              <el-input v-model="proofread.proofreaderName" disabled class="!w-220px" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="校对意见" prop="proofreaderOpinion">
              <el-input
                v-model="proofread.proofreaderOpinion"
                type="textarea"
                disabled
                class="!w-1000px"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div v-if="route.query.dictPrepareStatus ==50 || route.query.dictPrepareStatus ==10">
        <div>审核意见</div>
        <el-form class="-mb-5px" :model="examine" :inline="true" label-width="110px">
          <div>
            <el-form-item label="审核人" prop="approverName">
              <el-input v-model="examine.approverName" disabled class="!w-220px" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="审核意见" prop="approverOpinion">
              <el-input
                v-model="examine.approverOpinion"
                type="textarea"
                disabled
                class="!w-1000px"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </ContentWrap>
    <!-- 选择订单 -->
    <SelectOrder ref="formRefOrder" @success="getComponent" />
    <!-- 选择部件 -->
    <SelectComponent ref="formRefComponent" @success="addData" />
  </div>
</template>

<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { useRoute } from 'vue-router'
  import * as MarketingOrderInfoApi from '@/api/orderManagement/marketingOrderInfo'
  import * as ProductionPrepareApi from '@/api/produce/productManagement/productionPrepare'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import SelectOrder from './selectOrder.vue'
  import SelectComponent from './selectComponent.vue'
  const tagsViewStore = useTagsViewStore()
  const routes = useRouter() // 路由
  const route = useRoute()
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗
  const queryParam = reactive({
    id:undefined,
    orderNumber: undefined,
    dictOrderType: undefined,
    customerCode: undefined,
    customerName: undefined,
    productNumber: undefined,
    productName: undefined,
    productStandard: undefined,
    prepareNumber: undefined,
    dictPrepareStatus: undefined,
    taskOrderId:undefined,
    productionPrepareDetailCreateReqVOS: []
  })
  const proofread = reactive({
    proofreaderName: undefined,
    proofreaderOpinion: undefined
  })
  const examine = reactive({
    approverName: undefined,
    approverOpinion: undefined
  })
  const { push } = useRouter()
  const loading = ref(true)
  const list = ref<any>([])
  const formLoading = ref(false)
  let title = ref('新增订单信息')
  const tenantOptions = ref<any>([])
  const formRefOrder = ref()
  const handQueryOrder = () => {
    formRefOrder.value.open(queryParam.orderNumber)
  }
  const formRefComponent = ref()

  const chooseComponent = () => {
    if (
      queryParam.orderNumber != undefined &&
      queryParam.orderNumber != null &&
      queryParam.productNumber != null &&
      queryParam.productNumber != undefined
    ) {
      formRefComponent.value.open(queryParam.orderNumber, queryParam.productNumber,list.value)
    } else {
      message.warning('订单号和产品编号都不能为空')
    }
  }
  const addData = async (data) => {
    data.list.forEach(item => {
      item.partDrawingNumber = item.drawingNumber
      item.incomingId = item.id
    });
    list.value = data.list
    console.log(list.value)
  }
  const getList = async () => {
    loading.value = true
    try {
      // 请求数据的逻辑
    } finally {
      loading.value = false
    }
  }

  const deleteRow = (index: number) => {
    list.value.splice(index, 1)
  }
  //获取订单数据
  const getComponent = (data) => {
    // queryParam.id = data.list[0].id
    queryParam.orderNumber = data.list[0].orderNumber
    queryParam.dictOrderType = data.list[0].dictOrderType
    queryParam.customerCode = data.list[0].customerCode
    queryParam.customerName = data.list[0].customerName
    queryParam.productNumber = data.list[0].productNumber
    queryParam.productName = data.list[0].productName
    queryParam.productStandard = data.list[0].productStandard
    queryParam.prepareNumber = data.list[0].prepareNumber
    queryParam.taskOrderId = data.list[0].id
    list.value = []
  }

  //必填校验
  const check = async () => {
    let data = await list.value
    if (data.length) {
      for (let i = 0; i < data.length; i++) {
        console.log(data[i].prepareQuantity)
        if(data[i].prepareQuantity < 0 || !data[i].prepareQuantity) {
          message.warning(t('备货数量必须大于0且小于生产数量'))
          return false
        }else {
          if(Number(data[i].prepareQuantity) > Number(data[i].incomingRemaQuantity)) {
            message.warning(t('备货数量必须大于0且小于生产数量'))
            return false
          }
        }
      }
    } else {
      message.warning(t('请新增行'))
      return false
    }
    return true
    
  }
  /**保存 */
  const saveData = async () => {
    loading.value = true
    try {
      const isFlag = await check()
    if (isFlag) {
      let type = route.query.type
      queryParam.productionPrepareDetailCreateReqVOS = list.value
      if (type === 'create' || type === 'createShipmentOrder') {
        await ProductionPrepareApi.saveProductionPrepare(queryParam)
        message.success(t('common.createSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/produce/produce/productManagement/productionPrepare')
      } else {
        await ProductionPrepareApi.saveUpdateProductionPrepare(queryParam)
        message.success(t('common.createSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/produce/produce/productManagement/productionPrepare')
      }
    }
    } finally {
      loading.value = false
    }
    
  }
  /**提交 */
  const submitData = async () => {
    const isFlag = await check()
    if (isFlag) {
      let type = route.query.type
      queryParam.productionPrepareDetailCreateReqVOS = list.value
      console.log(queryParam)
      if (type === 'create') {
        await ProductionPrepareApi.submitProductionPrepare(queryParam)
        message.success(t('common.createSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/produce/produce/productManagement/productionPrepare')
      } else {
        await ProductionPrepareApi.submitProductionPrepare(queryParam)
        message.success(t('common.createSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/produce/produce/productManagement/productionPrepare')
      }
    }
  }
  /**作废 */
  const cancelData = async () => {
    queryParam.productionPrepareDetailCreateReqVOS = list.value
    await ProductionPrepareApi.cancelData(queryParam)
    message.success('作废成功')
    tagsViewStore.delView(routes.currentRoute.value)
    push('/produce/produce/productManagement/productionPrepare')
  }
  /**关闭 */
  const close = () => {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/produce/produce/productManagement/productionPrepare')
  }
  /**撤回 */
  const withdraw = async () => {
    queryParam.productionPrepareDetailCreateReqVOS = list.value
    await ProductionPrepareApi.withdraw(queryParam)
    message.success('撤回成功')
    tagsViewStore.delView(routes.currentRoute.value)
    push('/produce/produce/productManagement/productionPrepare')
  }
  //获取订单信息
  const getDetail = async (id) => {
    const data = await ProductionPrepareApi.getProductionPrepare(id)
    queryParam.id = data.id
    queryParam.orderNumber = data.orderNumber
    queryParam.dictOrderType = data.dictOrderType
    queryParam.customerCode = data.customerCode
    queryParam.customerName = data.customerName
    queryParam.productNumber = data.productNumber
    queryParam.productName = data.productName
    queryParam.productStandard = data.productStandard
    queryParam.prepareNumber = data.prepareNumber
    queryParam.dictPrepareStatus = data.dictPrepareStatus
    queryParam.id = data.id
    queryParam.taskOrderId = data.taskOrderId
    proofread.proofreaderName = data.proofreaderName
    proofread.proofreaderOpinion = data.proofreaderOpinion
    examine.approverName = data.approverName
    examine.approverOpinion = data.approverOpinion
    list.value = data.productionPrepareDetailRespVOS
  }
  const contentHeight = ref(0)
  const refreshData = async () => {
    formLoading.value = true
    contentHeight.value = document.body.clientHeight - 127
    formLoading.value = false
  }
  //获取部件档案
  const getCustomerProfileList = async () => {
    let params = {}
    const data = await MarketingOrderInfoApi.getCustomerProfileList(params)
    tenantOptions.value = data.list
  }
  // 初始化
  const tableHeight = ref(0)
  onMounted(async () => {
    tableHeight.value = document.body.clientHeight - 130
    refreshData()
    let type = route.query.type
    if (type === 'create') {
      title.value = '新增订单信息'
    } else if (type === 'createShipmentOrder') {
      queryParam.orderNumber = route.query.orderNumber
      queryParam.dictOrderType = Number(route.query.dictOrderType)
      queryParam.customerCode = route.query.customerCode
      queryParam.customerName = route.query.customerName
      queryParam.productNumber = route.query.productNumber
      queryParam.productName = route.query.productName
      queryParam.productStandard = route.query.productStandard
      queryParam.taskOrderId = route.query.id
    } else if (type === 'proofread') {
      if (route.query.id) {
        getDetail(route.query.id)
      }
    } else {
      if (route.query.id) {
        getDetail(route.query.id)
      }
    }

    await getList()
    await getCustomerProfileList()
  })
</script>
<style lang="scss" scoped>
  .contentView {
    padding: 10px;
    background: #fff;
  }

  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;

      .el-input__inner {
        cursor: default !important;
        text-align: center;
      }
    }
  }

  .btnWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .el-table .custom-header::before {
    content: '*';
    color: red;
    margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
  }

  .dropdown-width {
    width: 50px !important;
  }

  :deep(.el-form .el-input, .el-form .el-input__wrapper, .el-form .el-textarea) {
    width: 100% !important;
  }

  .select-wrapper {
    display: flex;
    align-items: center;
  }

  .search-icon {
    margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
    cursor: pointer;
    margin-top: 5px;
  }
</style>
